// GetPropertyFunction.cpp: implementation of the GetPropertyFunction class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "phsshare.h"
#include "GetPropertyFunction.h"
#include "DBConnectionManager.h"
#include "ProductCatalogManager.h"
#include "Part.h"
#include "SimpleExpression.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif


using namespace JointSystem;
using namespace DAWrapper;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

using namespace PropertySystem;

IMPLEMENT_DYNAMIC_CREATE(GetPropertyFunction, FunctionObject, FunctionObject::eGETPROPERTYFUNCTION);

GetPropertyFunction::GetPropertyFunction()
{

}

GetPropertyFunction::~GetPropertyFunction()
{
	
}

BOOL GetPropertyFunction::GetProperties()
{
	ASSERT(GetOwner());
	ASSERT(GetOwner()->IsKindOf(UE_RUNTIME_CLASS(Part)));

	Part* pPart = static_cast<Part*>(GetOwner());
	CString strSql;
	BOOL bResult = FALSE;

	ASSERT(!m_strSql.IsEmpty());
	try
	{
		ASSERT(m_rs == NULL);
		CString strDataSource;
		strDataSource = JointSystem::ProductCatalogManager::Instance()->
			GetProductCatalog(pPart->GetStandard())->DataSourceURI();
		ASSERT(!strDataSource.IsEmpty());
		_ConnectionPtr pCon = *DBConnectionManager::Instance()->GetConnectionPtrByUri(strDataSource);
		m_rs = pCon->Execute(_bstr_t(GetSql()), NULL, adCmdText);
		ASSERT(m_rs != NULL);
		if(!m_rs->adoEOF && !m_rs->BOF)
		{
			pPart->SetAvailable();
			bResult = this->InitProperty(*GetOwner());
		}
		else{
			pPart->SetUnavailable();
			this->Close();
			return FALSE;
		}
	}
	CATCH_COM_ERROR(m_rs, FALSE)

	this->Close();
	return bResult;
}

BOOL GetPropertyFunction::IsFill()
{
	BOOL bResult = TRUE;
	BOOL IsModify = FALSE;

	if(m_Condition.GetSize()==0)
		return TRUE;

	for(int i = 0; i < m_Condition.GetSize(); i++)
	{
		Variable* pVar = m_Condition.GetAt(i);
		ASSERT(pVar);
		if(!pVar->IsKnown())
		{
			bResult = FALSE;
			break;
		}
		else if(pVar->IsModify())
		{
			IsModify = TRUE;
		}
	}
	if(bResult&&IsModify)
		return TRUE;
	return FALSE;
}

void GetPropertyFunction::SetConditionKnown()
{
	for(int i = 0; i < m_Condition.GetSize(); i++)
	{
		m_Condition.GetAt(i)->SetKnown();
	}
}

CString GetPropertyFunction::GetSql()
{
	ASSERT(!m_strSql.IsEmpty());
	ASSERT(this->GetOwner());

	SimpleExpression expr(m_strSql, this->GetOwner()->GetPropertyStack());

	Variable var;
	var = expr.Caculate();

	return (CString)var;	
}

void GetPropertyFunction::ResetCondition()
{
	for(int i = 0; i < m_Condition.GetSize(); i++)
	{
		Variable* pVar = m_Condition.GetAt(i);
		ASSERT(pVar);
		pVar->SetKnown();
	}
}